import lodashCloneDeep from 'lodash/cloneDeep'
import lodashThrottle from 'lodash/throttle'
import lodashLast from 'lodash/last'

export const deepClone = lodashCloneDeep
export const throttle = (fn: (...args: any) => any, wait: number) =>
  lodashThrottle(fn, wait, { leading: true })

export const arrayLastItem = lodashLast

// 全局异常错误处理
export const trycatchInPromise = (fn: Function, location: string) => {
  try {
    fn()
  } catch (error) {
    console.log(`捕获位于${location}的错误`, error)
  }
}
/**
 * 知道一对键值对的情况下从对象数组中查找出对象
 * @param searchAarray 被查找的数据
 * @param target 键值对对象
 */
export const kvSearch = (
  searchAarray: Array<any>,
  target: { key: string; value: number | string },
) => {
  for (const i of searchAarray) {
    if (i[target.key] === target.value) return i
  }
  return void 0
}

export const UrlParameter = (parameter: string) => {
  const reg = new RegExp('(^|&)' + parameter + '=([^&]*)(&|$)')
  const r = window.location.search.substr(1).match(reg)
  if (r) return r[2]
  return ''
}
